/**
 * 渲染一个“群联系人”
 */
import { Tag } from 'antd'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { type BaseGroup } from '@/services/contact-types'
import { type QywxInfo } from '@/services/qywxs'
import './index.less'

export default function GroupItem(props: {
  contact: BaseGroup
  qywx?: Pick<QywxInfo, 'friendlyFullName'>
}) {
  const { contact, qywx } = props

  return qywx ? (
    <GroupItemContent contact={contact} qywx={qywx} />
  ) : (
    <GroupItemWithQywx contact={contact} />
  )
}

/**
 * 使用者未提供企业微信信息，自行拉取企业微信
 */
function GroupItemWithQywx(props: { contact: BaseGroup }) {
  const { contact } = props
  const [qywxs] = useStreams(services.qywxs.usables)
  const qywx = useMemo(
    () => qywxs.get(contact.ownerWxid) ?? { friendlyFullName: '' },
    [contact, qywxs],
  )
  return <GroupItemContent contact={contact} qywx={qywx} />
}

function GroupItemContent(props: { contact: BaseGroup; qywx: Pick<QywxInfo, 'friendlyFullName'> }) {
  const { contact, qywx } = props

  return <div className="qun-group-item">
    <img src={defaultAvatar} className="qun-group-item-avatar" />
    <div className="qun-group-item-info">
      <div className="qun-group-item-info-inner">
        <span className="qun-group-item-name">{contact.name}</span>
        {contact.isExternal ? <Tag>外部群</Tag> : null}
        {contact.isOwner ? <Tag>群主</Tag> : null}
      </div>
      <div className="qun-group-item-owner">{qywx.friendlyFullName}</div>
    </div>
  </div>
}
